package com.gigi.datageniebackendmaster.mq;

import cn.hutool.core.util.StrUtil;
import com.gigi.datageniebackendmaster.common.AiManager;
import com.gigi.datageniebackendmaster.common.Constant;
import com.gigi.datageniebackendmaster.exception.BusinessException;
import com.gigi.datageniebackendmaster.model.entity.ChartEntity;
import com.gigi.datageniebackendmaster.model.enums.ChartStatusEnum;
import com.gigi.datageniebackendmaster.model.enums.ErrorCodeEnum;
import com.gigi.datageniebackendmaster.service.ChartService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * BI 消息消费者
 */
@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {

        // 1、接收消息
        log.info("receiveMessage message = {}", message);
        if (StrUtil.isBlank(message)) {
            // 如果消息为空，则拒绝消息，并丢弃，抛异常
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCodeEnum.SYSTEM_ERROR, "消息为空");
        }

        // 2、解析消息，获取 chartId
        long chartId = Long.parseLong(message);

        // 3、根据 chartId 查询图表信息
        ChartEntity chart = chartService.getById(chartId);
        if (Objects.isNull(chart)) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCodeEnum.NOT_FOUND_ERROR);
        }

        // 4、先将数据库状态改为 “执行中”
        ChartEntity target = new ChartEntity();
        target.setId(chartId);
        target.setStatus(ChartStatusEnum.RUNNING.getCode());
        if (!chartService.updateById(target)) {
            chartService.handleUpdateError(chartId, "更新图表执行中状态失败");
        }

        // 5、构造提词
        String goal = chart.getGoal();
        StringBuffer userInput = new StringBuffer();
        if (StrUtil.isNotBlank(chart.getType())) {
            goal += ",用" + chart.getType();
        }
        userInput.append("分析诉求:").append(StrUtil.LF).append(goal).append(StrUtil.LF);
        userInput.append("原始数据:").append(StrUtil.LF).append(chart.getRawData());

        // 6、调AI
        String result = aiManager.doChat(Constant.BI_MODEL_ID, userInput.toString());

        // 7、处理结果
        String[] splits = result.split("【【【【");
        if (splits.length < 3) {
            chartService.handleUpdateError(chartId, "AI 生成格式错误");
        }
        String resultChart = splits[1].trim();
        String resultText = splits[2].trim();

        // 8、更新数据库
        ChartEntity updateTarget = new ChartEntity();
        updateTarget.setId(chartId);
        updateTarget.setResultChart(resultChart);
        updateTarget.setResultText(resultText);
        updateTarget.setStatus(ChartStatusEnum.SUCCEED.getCode());
        if (!chartService.updateById(updateTarget)) {
            chartService.handleUpdateError(chartId, "更新图表成功状态失败");
        }

        // 9、消息确认
        channel.basicAck(deliveryTag, false);
    }

}
